from flask import current_app, jsonify
from flask import g
from flask import render_template
from flask import request
from flask import session
from sqlalchemy.sql.functions import user

from info.Modules.index import blue_index

from info.models import User, News, Category

#新闻内容显示
from info.utils.common_grep import user_login_data
from info.utils.response_code import RET


@blue_index.route('/news_list')
def news_list():
    """
   +    0、获取数据
   +    0.1 校验数据
   +    1、查询出所有新闻 (查询对应分类的新闻)
   +    2、排序 按照创建时间
   +    3、分页
   +    :return:
   +    """
#0、获取数据
    cid = request.args.get("cid",'1')
    page = request.args.get("page",'1')
    per_page = request.args.get("per_page",'4')
#0.1 校验数据
    try:

        cid = int(cid)
        page =int(page)
        per_page = int(per_page)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno = RET.PARAMERR,errmsg ='参数错了')
#1、查询出所有新闻 (查询对应分类的新闻)
    if cid ==1:
        mew_list = News.query.order_by(News.create_time.desc()).paginate(page,per_page)

    else:
        mew_list = News.query.filter(News.category_id == cid).order_by(News.create_time.desc()).paginate(page,per_page)

    news_list = mew_list.items
    news_dict =[]
    for new_obj in news_list:
        news_dict.append(new_obj.to_dict())
    data ={
        'news_dict_li':news_dict
    }
    return jsonify(errno = RET.OK,errmsg ='成功',data =data)
#2、排序 按照创建时间
#3、分页




#实现右上角用户信息
@blue_index.route('/')
@user_login_data
def index():
    """
        一、显示用户登录状态   核心逻辑：查询出来用户信息，然后通过模板进行渲染
        :return:
        """
    # user_id =session.get('user_id')
    # print(user_id)
    # user =None
    # if user_id:
    #     try:
    #         user = User.query.get(user_id)
    #     except Exception as e:
    #         current_app.logger.error(e)
    user =g.user


# 新闻点击排行功能实现
    # 1、查询出来所有的新闻数据
    # 2、进行排序？？？按点击量排序
    # 3、取出前六条新闻
    # 4、渲染
    news_list = News.query.order_by(News.clicks.desc()).limit(6).all()  # 对象列表[obj, obj, obj]
    # 5、将对象列表转化为字典列表
    news_dict = []
    for news_obj in news_list:
        news_dict.append(news_obj.to_dict())

# 三、查询分类
    categorys = Category.query.all()
    # 5、将对象列表转化为字典列表
    categorys_dict =[]
    for category_obj in categorys:
        categorys_dict.append(category_obj)
    # print(categorys_dict)

    data = {"user_info": user.to_dict() if user else None,
            'news_dict':news_dict,
            'categorys_dict':categorys_dict

            }
    print(news_dict)




    return render_template('news/index.html' ,data =data)

@blue_index.route("/favicon.ico")
def favicon():

    return current_app.send_static_file('news/favicon.ico')